#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
 
#include "data_type.h"
#include "cube.h"
#include "cube_define.h"
#include "cube_record.h"
#include "cubemem_struct.h"
#include "memcheck.h"
// add para lib_include
int memcheck_init(void * sub_proc, void * para)
{
	int ret;
	// add yorself's module init func here
	return 0;
}
int memcheck_start(void * sub_proc, void * para)
{
	int ret;
	void * recv_msg;
	int type;
	int subtype;
	// add yorself's module exec func here
	while(1)
	{
		usleep(time_val.tv_usec);
		ret=ex_module_recvmsg(sub_proc,&recv_msg);
		if(ret<0)
			continue;
		if(recv_msg==NULL)
			continue;
		type=message_get_type(recv_msg);
		subtype=message_get_subtype(recv_msg);
		if(!memdb_find_recordtype(type,subtype))
		{
			printf("message format (%d %d) is not registered!\n",
			message_get_type(recv_msg),message_get_subtype(recv_msg));
			continue;
		}
		if((type==TYPE(GENERAL_RETURN))&&(subtype==SUBTYPE(GENERAL_RETURN,STRING)))
		{
			ret=proc_analysis_memfile(sub_proc,recv_msg);
		}
	}
	return 0;
}

int proc_analysis_memfile(void * sub_proc,void * recv_msg)
{
	int ret;
    int fd;
    int offset=0;
    BYTE membuf[1024];
    void * memcheck_template;
    void * new_msg;

	RECORD(GENERAL_RETURN,STRING) * memcheck_notice;
	RECORD(MEM_CHECK,ROOT_STRUCT) * root_struct;
	
	ret=message_get_record(recv_msg,&memcheck_notice,0);
	if(ret<0)
		return ret;

    fd=open(memcheck_notice->return_value,O_RDONLY);
    if(fd<0)
        return -EINVAL;

    memcheck_template=memdb_get_template(TYPE_PAIR(MEM_CHECK,ROOT_STRUCT));
    if(memcheck_template==NULL)
        return -EINVAL;

    ret=read(fd,membuf,1024);

    root_struct=Talloc0(sizeof(*root_struct));
    if(root_struct==NULL)
        return -ENOMEM;

    ret=blob_2_struct(membuf+offset,root_struct,memcheck_template);
    if(ret<=0)
        return -EINVAL;
    offset+=ret;
    
    new_msg=message_create(TYPE_PAIR(MEM_CHECK,ROOT_STRUCT),recv_msg);
    //new_msg=message_create(TYPE_PAIR(MEM_CHECK,ROOT_STRUCT),NULL);

    message_add_record(new_msg,root_struct);
	
	ret=ex_module_sendmsg(sub_proc,new_msg);
	return ret;
}
